HTTPS मॉड्यूल का परिचय
HTTPS मॉड्यूल Node.js का एक महत्वपूर्ण मॉड्यूल है जो HTTPS प्रोटोकॉल का कार्यान्वयन प्रदान करता है, जो मूल रूप से TLS/SSL पर HTTP है।
यह HTTP मॉड्यूल का एक सुरक्षित संस्करण है जो शाखाओं और सर्वर के बीच एन्क्रिप्टेड संचार प्रदान करता है।
डेटा एन्क्रिप्शन
चुभती नजरों से बचाता है
सर्वर प्रमाणीकरण
सर्वर की पहचान सत्यापित करना
आंकड़ा शुचिता
डेटा परिवर्तन या भ्रष्टाचार को रोकता है
HTTPS का उपयोग क्यों करें?
HTTPS आधुनिक वेब अनुप्रयोगों के लिए महत्वपूर्ण है क्योंकि यह:
नोट:
आधुनिक HTTPS TLS (ट्रांसपोर्ट लेयर सिक्योरिटी) का उपयोग करता है, जो SSL (सिक्योर सॉकेट लेयर) का उत्तराधिकारी है। इन शब्दों का प्रयोग अक्सर एक दूसरे के स्थान पर किया जाता है, लेकिन एसएसएल को अब अप्रचलित माना जाता है।
महत्वपूर्ण:
2023 तक, सभी प्रमुख ब्राउज़रों को नई वेब सुविधाओं और एपीआई के लिए HTTPS की आवश्यकता होगी। कई ब्राउज़र बिना HTTPS वाली साइटों को भी "असुरक्षित" के रूप में चिह्नित करते हैं।
HTTPS कैसे काम करता है
HTTPS के साथ शुरुआत करना
मॉड्यूल आयात कर रहा है
अपने Node.js एप्लिकेशन में HTTPS मॉड्यूल का उपयोग करने के लिए, आप इसे CommonJS या ES मॉड्यूल व्याकरण का उपयोग करके आयात कर सकते हैं:
CommonJS (Node.js default)
// Using require()
const https = require('https');
ES Modules (Node.js 14+)
// Using import (requires "type": "module" in package.json)
import https from 'https';
HTTPS vs HTTP API
HTTPS मॉड्यूल का इंटरफ़ेस HTTP मॉड्यूल के समान है, मुख्य अंतर यह है कि यह कनेक्शन स्थापित करने के लिए TLS/SSL का उपयोग करता है।
इसका मतलब यह है कि HTTP मॉड्यूल में उपलब्ध सभी विधियाँ और घटनाएँ HTTPS मॉड्यूल में उपलब्ध हैं।
नोट:
उपयोग में मुख्य अंतर यह है कि HTTPS को SSL/TLS प्रमाणपत्र की आवश्यकता होती है, जबकि HTTP के लिए नहीं।
एसएसएल/टीएलएस प्रमाणपत्र
HTTPS को सुरक्षित कनेक्शन स्थापित करने के लिए SSL/TLS प्रमाणपत्र की आवश्यकता होती है। प्रमाणपत्र कई प्रकार के होते हैं:
| सर्टिफिकेट टाइप | आवेदन | सत्यापन स्थिति |
|---|---|---|
| स्व-हस्ताक्षरित प्रमाण पत्र | विकास और परीक्षण के लिए (ब्राउज़रों द्वारा विश्वसनीय नहीं) | कोई सत्यापन नहीं |
| डोमेन सत्यापित (DV) | बुनियादी सत्यापन केवल डोमेन स्वामित्व की पुष्टि करता है | डोमेन स्वामित्व |
| संगठन सत्यापित (OV) | सिस्टम विवरण का सत्यापन | सिस्टम विवरण |
| विस्तारित सत्यापन (ईवी) | सत्यापन का उच्च स्तर ब्राउज़र में कंपनी का नाम प्रदर्शित करता है | पूर्ण कानूनी सत्यापन |
| वाइल्डकार्ड प्रमाणपत्र | किसी डोमेन के सभी उपडोमेन की सुरक्षा करता है | डोमेन और सभी उपडोमेन |
| मल्टी-डोमेन (SAN) प्रमाणपत्र | एक प्रमाणपत्र से एकाधिक डोमेन की सुरक्षा करता है | एकाधिक डोमेन |
स्व-हस्ताक्षरित प्रमाण पत्र बनाना
विकास के लिए, आप ओपनएसएसएल का उपयोग करके स्व-हस्ताक्षरित प्रमाणपत्र तैयार कर सकते हैं:
एक बुनियादी स्व-हस्ताक्षरित प्रमाणपत्र
# Generate a private key (RSA 2048-bit)
openssl genrsa -out key.pem 2048
# Generate a self-signed certificate (valid for 365 days)
openssl req -new -x509 -key key.pem -out cert.pem -days 365 -nodes
विषय वैकल्पिक नाम (SAN) के साथ।
# Create a config file (san.cnf)
cat > san.cnf << EOF
[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = State
L = City
O = Organization
OU = Organizational Unit
CN = localhost
[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = localhost
IP.1 = 127.0.0.1
EOF
# Generate key and certificate with SAN
openssl req -x509 -nodes -days 365 -newkey rsa:2048 \
-keyout key.pem -out cert.pem -config san.cnf -extensions 'v3_req'
सुरक्षा नोट:
स्व-हस्ताक्षरित प्रमाणपत्र ब्राउज़र में सुरक्षा चेतावनियाँ ट्रिगर कर सकते हैं क्योंकि वे किसी विश्वसनीय प्रमाणपत्र प्राधिकारी द्वारा हस्ताक्षरित नहीं हैं।
उनका उपयोग केवल विकास और परीक्षण उद्देश्यों के लिए करें।
विश्वसनीय प्रमाणपत्र प्राप्त करना
उत्पादन के लिए, विश्वसनीय प्रमाणन प्राधिकारियों से प्रमाणपत्र प्राप्त करें:
वेतनभोगी सीए
डिजीसर्ट, ग्लोबलसाइन, कोमोडो, आदि
निःशुल्क सीए
Let's Encrypt, ZeroSSL, Cloudflare
Let's Encrypt:
लेट्स एनक्रिप्ट एक लोकप्रिय मुफ़्त, स्वचालित और खुला प्रमाणपत्र प्राधिकरण है जो विश्वसनीय प्रमाणपत्र प्रदान करता है।
एक HTTPS सर्वर बनाना
जब आपके पास अपना एसएसएल/टीएलएस प्रमाणपत्र तैयार हो, तो आप Node.js में एक HTTPS सर्वर बना सकते हैं।
HTTPS सर्वर एपीआई HTTP सर्वर एपीआई के समान है, मुख्य अंतर एसएसएल/टीएलएस आर्किटेक्चर है।
मूल HTTPS सर्वर उदाहरण
const https = require('https');
const fs = require('fs');
const path = require('path');
// Path to your SSL/TLS certificate and key
const sslOptions = {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
// Enable all security features
minVersion: 'TLSv1.2',
// Recommended security settings
secureOptions: require('constants').SSL_OP_NO_SSLv3 |
require('constants').SSL_OP_NO_TLSv1 |
require('constants').SSL_OP_NO_TLSv1_1
};
// Create the HTTPS server
const server = https.createServer(sslOptions, (req, res) => {
// Security headers
res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
// Handle different routes
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('Welcome to the Secure Server
Your connection is encrypted!
');
} else if (req.url === '/api/status') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok', time: new Date().toISOString() }));
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Handle server errors
server.on('error', (error) => {
console.error('Server error:', error);
});
// Start the server on port 3000 (HTTPS default is 443 but requires root)
const PORT = process.env.PORT || 3000;
server.listen(PORT, '0.0.0.0', () => {
console.log(`Server running at https://localhost:${PORT}`);
console.log('Press Ctrl+C to stop the server');
});
नोट:
यूनिक्स जैसी प्रणालियों पर, 1024 से कम पोर्ट को रूट अनुमतियों की आवश्यकता होती है। उत्पादन के लिए, Node.js को उच्च पोर्ट (3000, 8080, आदि) पर चलाना और SSL समाप्ति के लिए Nginx या Apache जैसे रिवर्स प्रॉक्सी का उपयोग करना आम बात है।
उन्नत सर्वर कॉन्फ़िगरेशन
उत्पादन परिवेश के लिए, आपको उन्नत एसएसएल/टीएलएस कॉन्फ़िगरेशन की आवश्यकता हो सकती है:
ओसीएसपी स्टेपलिंग और सत्र बहाली के साथ उन्नत HTTPS सर्वर
const https = require('https');
const fs = require('fs');
const path = require('path');
const tls = require('tls');
// Path to your SSL/TLS files
const sslOptions = {
// Certificate and key
key: fs.readFileSync(path.join(__dirname, 'privkey.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
ca: [
fs.readFileSync(path.join(__dirname, 'chain.pem'))
],
// Recommended security settings
minVersion: 'TLSv1.2',
maxVersion: 'TLSv1.3',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256',
'ECDHE-ECDSA-AES256-GCM-SHA384',
'ECDHE-RSA-AES256-GCM-SHA384',
'ECDHE-ECDSA-CHACHA20-POLY1305',
'ECDHE-RSA-CHACHA20-POLY1305',
'ECDHE-ECDSA-AES128-GCM-SHA256',
'ECDHE-RSA-AES128-GCM-SHA256'
].join(':'),
honorCipherOrder: true,
// Enable OCSP Stapling
requestCert: true,
rejectUnauthorized: true,
// Enable session resumption
sessionTimeout: 300, // 5 minutes
sessionIdContext: 'my-secure-app'
};
// Create the HTTPS server
const server = https.createServer(sslOptions, (req, res) => {
// Security headers
const securityHeaders = {
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains; preload',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'Content-Security-Policy': "default-src 'self'",
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), microphone=(), camera=()',
};
Object.entries(securityHeaders).forEach(([key, value]) => {
res.setHeader(key, value);
});
// Handle requests
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
res.end('Secure Node.js Server
Your connection is secure!
');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
// Handle server errors
server.on('error', (error) => {
console.error('Server error:', error);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught exception:', error);
// Perform graceful shutdown
server.close(() => process.exit(1));
});
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Handle graceful shutdown
const gracefulShutdown = () => {
console.log('Shutting down gracefully...');
server.close(() => {
console.log('Server closed');
process.exit(0);
});
// Force close server after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
};
// Listen for shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
// Start the server
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
server.listen(PORT, HOST, () => {
const { address, port } = server.address();
console.log(`Server running at https://${address}:${port}`);
// Output server information
console.log('Node.js version:', process.version);
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('PID:', process.pid);
});
सुरक्षा सर्वोत्तम प्रथाएँ:
- सुरक्षा अद्यतनों के लिए हमेशा Node.js के नवीनतम स्थिर संस्करण का उपयोग करें
npm auditऔरnpm updateका उपयोग करके अपनी निर्भरताएँ अद्यतन रखें- संवेदनशील कॉन्फ़िगरेशन के लिए पर्यावरण चर का उपयोग करें (संस्करण नियंत्रण के लिए कभी रहस्य न रखें)
- दुरुपयोग रोकने के लिए रेट कैपिंग लागू करें
- अपने एसएसएल/टीएलएस प्रमाणपत्रों को नियमित रूप से घुमाएँ
- सुरक्षा कमजोरियों के लिए अपने सर्वर की निगरानी करें
- अतिरिक्त सुरक्षा सुविधाओं के लिए उत्पादन में Nginx या Apache जैसे रिवर्स प्रॉक्सी का उपयोग करें
आपके HTTPS सर्वर का परीक्षण
अपने HTTPS सर्वर का परीक्षण करने के लिए, आप कर्ल या वेब ब्राउज़र का उपयोग कर सकते हैं:
कर्ल का उपयोग करना
# Skip certificate verification (for self-signed certs)
curl -k https://localhost:3000
# With certificate verification (for trusted certs)
curl --cacert /path/to/ca.pem https://yourdomain.com
वेब ब्राउज़र का उपयोग करना
# अपना वेब ब्राउज़र खोलें और https://localhost:3000 पर नेविगेट करें # यदि स्व-हस्ताक्षरित प्रमाणपत्र का उपयोग कर रहे हैं तो सुरक्षा चेतावनी स्वीकार करें # एन्हांसमेंट के लिए, आप अपने स्व-हस्ताक्षरित प्रमाणपत्र को विश्वसनीय रूट प्रमाणपत्रों में जोड़ सकते हैं
HTTPS अनुरोध करना
HTTPS मॉड्यूल आपको अन्य सर्वरों के लिए सुरक्षित HTTP अनुरोध करने की अनुमति देता है।
सुरक्षित एपीआई और वेब सेवाओं के साथ संचार करने के लिए यह आवश्यक है।
एक बुनियादी GET अनुरोध
const https = require('https');
const { URL } = require('url');
// Parse the target URL
const apiUrl = new URL('https://api.example.com/data');
// Request options
const options = {
hostname: apiUrl.hostname,
port: 443,
path: apiUrl.pathname + apiUrl.search,
method: 'GET',
headers: {
'User-Agent': 'MySecureApp/1.0',
'Accept': 'application/json',
'Cache-Control': 'no-cache'
},
// Security settings
rejectUnauthorized: true, // Verify the server certificate (default: true)
// Timeout in milliseconds
timeout: 10000, // 10 seconds
};
console.log(`Making request to: https://${options.hostname}${options.path}`);
// Make the HTTPS request
const req = https.request(options, (res) => {
const { statusCode, statusMessage, headers } = res;
const contentType = headers['content-type'] || '';
console.log(`Status: ${statusCode} ${statusMessage}`);
console.log('Headers:', headers);
// Handle redirects
if (statusCode >= 300 && statusCode < 400 && headers.location) {
console.log(`Redirecting to: ${headers.location}`);
// In a real app, you'd handle the redirect
res.resume(); // Discard the response body
return;
}
// Check for successful response
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed.\nStatus Code: ${statusCode}`);
} else if (!/^application\/json/.test(contentType)) {
error = new Error(`Invalid content-type.\nExpected application/json but received ${contentType}`);
}
if (error) {
console.error(error.message);
res.resume(); // Consume response data to free up memory
return;
}
// Process the response
let rawData = '';
res.setEncoding('utf8');
// Collect chunks of data
res.on('data', (chunk) => {
rawData += chunk;
});
// Process the complete response
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log('Response data:', parsedData);
} catch (e) {
console.error('Error parsing JSON:', e.message);
}
});
});
// Handle request errors
req.on('error', (e) => {
console.error(`Request error: ${e.message}`);
});
// End the request (required to send it)
req.end();
सरल अनुरोधों के लिए https.get() का उपयोग करना
const https = require('https');
const { URL } = require('url');
// Parse the URL
const url = new URL('https://jsonplaceholder.typicode.com/posts/1');
// Request options
const options = {
hostname: url.hostname,
path: url.pathname,
method: 'GET',
headers: {
'Accept': 'application/json',
'User-Agent': 'MySecureApp/1.0'
}
};
console.log(`Fetching data from: ${url}`);
// Make the GET request
const req = https.get(options, (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
if (statusCode !== 200) {
console.error(`Request failed with status code: ${statusCode}`);
res.resume(); // Consume response data to free up memory
return;
}
if (!/^application\/json/.test(contentType)) {
console.error(`Expected JSON but got ${contentType}`);
res.resume();
return;
}
let rawData = '';
res.setEncoding('utf8');
// Collect data chunks
res.on('data', (chunk) => {
rawData += chunk;
});
// Process complete response
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log('Received data:', parsedData);
} catch (e) {
console.error('Error parsing JSON:', e.message);
}
});
});
// Handle errors
req.on('error', (e) => {
console.error(`Error: ${e.message}`);
});
// Set a timeout
req.setTimeout(10000, () => {
console.error('Request timeout');
req.destroy();
});
उदाहरण आउटपुट:
Response: {
userId: 1,
id: 1,
title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
POST अनुरोध करना
const https = require('https');
const { URL } = require('url');
// Request data
const postData = JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
});
// Parse the URL
const url = new URL('https://jsonplaceholder.typicode.com/posts');
// Request options
const options = {
hostname: url.hostname,
port: 443,
path: url.pathname,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData),
'User-Agent': 'MySecureApp/1.0',
'Accept': 'application/json'
},
timeout: 10000 // 10 seconds
};
console.log('Sending POST request to:', url.toString());
// Create the request
const req = https.request(options, (res) => {
console.log(`Status Code: ${res.statusCode}`);
console.log('Headers:', res.headers);
let responseData = '';
res.setEncoding('utf8');
// Collect response data
res.on('data', (chunk) => {
responseData += chunk;
});
// Process complete response
res.on('end', () => {
try {
const parsedData = JSON.parse(responseData);
console.log('Response:', parsedData);
} catch (e) {
console.error('Error parsing response:', e.message);
}
});
});
// Handle errors
req.on('error', (e) => {
console.error(`Request error: ${e.message}`);
});
// Set a timeout
req.setTimeout(15000, () => {
req.destroy(new Error('Request timeout after 15 seconds'));
});
// Write data to request body
req.write(postData);
// End the request
req.end();
HTTPS अनुरोधों के लिए सर्वोत्तम अभ्यास:
- अनुरोध में भेजने से पहले इनपुट डेटा को हमेशा जांचें और परिष्कृत करें
- एपीआई कुंजियों जैसी संवेदनशील जानकारी के लिए पर्यावरण चर का उपयोग करें
- उचित त्रुटि प्रबंधन और समय संबंधी निर्णय लागू करें
- उपयुक्त शीर्षलेख सेट करें (सामग्री-प्रकार, स्वीकार करें, उपयोगकर्ता-एजेंट)
- रीडायरेक्ट को सही ढंग से संभालें (3xx स्थिति कोड)
- अस्थायी विफलताओं के लिए पुनः प्रयास तर्क लागू करें
- अधिक जटिल स्थितियों के लिए axios या node-fetch जैसी लाइब्रेरी का उपयोग करें
Express.js के साथ HTTPS सर्वर
आप महत्वपूर्ण HTTPS मॉड्यूल का सीधे उपयोग कर सकते हैं, लेकिन अधिकांश Node.js एप्लिकेशन HTTP/HTTPS अनुरोधों को संभालने के लिए Express.js जैसे वेब फ्रेमवर्क का उपयोग करते हैं।
Express.js के साथ एक बुनियादी HTTPS सर्वर
const express = require('express');
const https = require('https');
const fs = require('fs');
const path = require('path');
const helmet = require('helmet'); // Security middleware
// Create Express app
const app = express();
// Security middleware
app.use(helmet());
// Parse JSON and URL-encoded bodies
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// Serve static files from 'public' directory
app.use(express.static(path.join(__dirname, 'public'), {
dotfiles: 'ignore',
etag: true,
extensions: ['html', 'htm'],
index: 'index.html',
maxAge: '1d',
redirect: true
}));
// Routes
app.get('/', (req, res) => {
res.send('Welcome to Secure Express Server
');
});
app.get('/api/status', (req, res) => {
res.json({
status: 'operational',
timestamp: new Date().toISOString(),
environment: process.env.NODE_ENV || 'development',
nodeVersion: process.version
});
});
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Not Found' });
});
// SSL/TLS options
const sslOptions = {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
// Enable HTTP/2 if available
allowHTTP1: true,
// Recommended security options
minVersion: 'TLSv1.2',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256',
'ECDHE-RSA-AES128-GCM-SHA256',
'!DSS',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!3DES',
'!MD5',
'!PSK'
].join(':'),
honorCipherOrder: true
};
// Create HTTPS server
const PORT = process.env.PORT || 3000;
const server = https.createServer(sslOptions, app);
// Handle unhandled promise rejections
process.on('unhandledRejection', (reason, promise) => {
console.error('Unhandled Rejection at:', promise, 'reason:', reason);
});
// Handle uncaught exceptions
process.on('uncaughtException', (error) => {
console.error('Uncaught Exception:', error);
// Perform cleanup and exit if needed
process.exit(1);
});
// Graceful shutdown
const gracefulShutdown = (signal) => {
console.log(`\nReceived ${signal}. Shutting down gracefully...`);
server.close(() => {
console.log('HTTP server closed.');
// Close database connections, etc.
process.exit(0);
});
// Force close server after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
};
// Listen for shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
// Start the server
const HOST = process.env.HOST || '0.0.0.0';
server.listen(PORT, HOST, () => {
console.log(`Express server running at https://${HOST}:${PORT}`);
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('Press Ctrl+C to stop the server');
});
पर्यावरण चर का उपयोग करना
.env फ़ाइल
NODE_ENV=development
PORT=3000
HOST=0.0.0.0
SSL_KEY_PATH=./key.pem
SSL_CERT_PATH=./cert.pem
पर्यावरण चर लोड हो रहा है
require('dotenv').config();
// Access environment variables
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '0.0.0.0';
const sslOptions = {
key: fs.readFileSync(process.env.SSL_KEY_PATH),
cert: fs.readFileSync(process.env.SSL_CERT_PATH)
// ... other options
};
उत्पादन विस्तार
उत्पादन में, आपके Node.js एप्लिकेशन के सामने Nginx या Apache जैसे रिवर्स प्रॉक्सी का उपयोग करने की अनुशंसा की जाती है। यह प्रदान करता है:
उदाहरण Nginx कॉन्फ़िगरेशन
server {
listen 443 ssl http2;
server_name yourdomain.com;
# SSL configuration
ssl_certificate /path/to/your/cert.pem;
ssl_certificate_key /path/to/your/key.pem;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-XSS-Protection "1; mode=block" always;
# Proxy to Node.js app
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# Serve static files directly
location /static/ {
root /path/to/your/app/public;
expires 30d;
access_log off;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
server_name yourdomain.com;
return 301 https://$host$request_uri;
}
Express.js HTTPS :
- सुरक्षा विषयों के लिए हेलमेट मिडलवेयर का उपयोग कब करें
- सुरक्षित सत्र विकल्प सेट करें (यदि सत्र का उपयोग कर रहे हैं)
- कॉन्फ़िगरेशन के लिए पर्यावरण चर का उपयोग करें
- उचित त्रुटि प्रबंधन और लॉगिंग लागू करें
- उत्पादन में रिवर्स प्रॉक्सी का उपयोग करें
- अपने पूर्वाग्रह चिरस्थायी रखें
- सर्वोत्तम प्रदर्शन के लिए HTTP/2 का उपयोग करें
- दुरुपयोग रोकने के लिए रेट कैपिंग लागू करें
- यदि आपका एपीआई विभिन्न डोमेन से एक्सेस किया गया है तो CORS मिडलवेयर का उपयोग करें
Node.js के साथ HTTP/2
HTTP/2 HTTP प्रोटोकॉल का एक महत्वपूर्ण संशोधन है जो HTTP/1.1 की तुलना में महत्वपूर्ण प्रदर्शन सुधार प्रदान करता है। HTTPS के साथ संयुक्त, यह आधुनिक वेब अनुप्रयोगों के लिए सुरक्षा और प्रदर्शन लाभ प्रदान करता है।
HTTP/2 के लाभ
HTTP/2 सर्वर उदाहरण
const http2 = require('http2');
const fs = require('fs');
const path = require('path');
// SSL/TLS options
const serverOptions = {
key: fs.readFileSync(path.join(__dirname, 'key.pem')),
cert: fs.readFileSync(path.join(__dirname, 'cert.pem')),
allowHTTP1: true, // Fallback to HTTP/1.1 if needed
// Recommended security settings
minVersion: 'TLSv1.2',
ciphers: [
'TLS_AES_256_GCM_SHA384',
'TLS_CHACHA20_POLY1305_SHA256',
'TLS_AES_128_GCM_SHA256',
'ECDHE-ECDSA-AES256-GCM-SHA384',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!3DES',
'!MD5',
'!PSK'
].join(':'),
honorCipherOrder: true
};
// Create HTTP/2 server
const server = http2.createSecureServer(serverOptions);
// Handle incoming requests
server.on('stream', (stream, headers) => {
const method = headers[':method'];
const path = headers[':path'];
const scheme = headers[':scheme'];
const authority = headers[':authority'];
console.log(`${method} ${path} (HTTP/2)`);
// Handle different routes
if (path === '/') {
// Set response headers
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200,
'x-powered-by': 'Node.js HTTP/2',
'cache-control': 'public, max-age=3600'
});
// Send HTML response
stream.end(`
HTTP/2 Server
Hello from HTTP/2 Server!
This page is served over HTTP/2.
Loading data...
`);
}
// API endpoint
else if (path === '/api/data' && method === 'GET') {
stream.respond({
'content-type': 'application/json',
':status': 200,
'cache-control': 'no-cache'
});
stream.end(JSON.stringify({
message: 'Data from HTTP/2 API',
timestamp: new Date().toISOString(),
protocol: 'HTTP/2',
server: 'Node.js HTTP/2 Server'
}));
}
// Server Push example
else if (path === '/push') {
// Push additional resources
stream.pushStream({ ':path': '/styles.css' }, (err, pushStream) => {
if (err) {
console.error('Push stream error:', err);
return;
}
pushStream.respond({
'content-type': 'text/css',
':status': 200
});
pushStream.end('body { font-family: Arial, sans-serif; margin: 2em; }');
});
stream.respond({
'content-type': 'text/html; charset=utf-8',
':status': 200
});
stream.end('Server Push Example
');
}
// 404 Not Found
else {
stream.respond({
'content-type': 'text/plain',
':status': 404
});
stream.end('404 - Not Found');
}
});
// Handle errors
server.on('error', (err) => {
console.error('Server error:', err);
process.exit(1);
});
// Start the server
const PORT = process.env.PORT || 8443;
server.listen(PORT, '0.0.0.0', () => {
console.log(`HTTP/2 server running at https://localhost:${PORT}`);
console.log('Environment:', process.env.NODE_ENV || 'development');
console.log('Press Ctrl+C to stop the server');
});
// Graceful shutdown
const gracefulShutdown = (signal) => {
console.log(`\nReceived ${signal}. Shutting down gracefully...`);
server.close(() => {
console.log('HTTP/2 server closed.');
process.exit(0);
});
// Force close server after 10 seconds
setTimeout(() => {
console.error('Forcing shutdown...');
process.exit(1);
}, 10000);
};
// Listen for shutdown signals
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);
नोट:
HTTP/2 को ब्राउज़र में HTTPS की आवश्यकता होती है, प्रोटोकॉल को स्वयं एन्क्रिप्शन की आवश्यकता नहीं होती है। सभी प्रमुख ब्राउज़र टीएलएस (एचटीटीपीएस) पर केवल HTTP/2 का समर्थन करते हैं।
HTTP और HTTPS की तुलना करना
| विशेषता | HTTP | HTTPS |
|---|---|---|
| डेटा एन्क्रिप्शन | नहीं (सादा पाठ) | हाँ (एन्क्रिप्टेड) |
| सर्वर प्रमाणीकरण | नहीं | हाँ (प्रमाणपत्र के माध्यम से) |
| आंकड़ा शुचिता | कोई सुरक्षा नहीं | संरक्षित (सुधार पाया गया) |
| डिफ़ॉल्ट पोर्ट | 80 | 443 |
| प्रदर्शन | तेज़ | थोड़ा सा अवलोकन (लेकिन HTTP/2 के साथ बेहतर हुआ) |
| एसईओ रैंकिंग | कम | अधिक (Google HTTPS को प्राथमिकता देता है) |
| व्यवस्था जटिल है | सरल | अधिक जटिल (प्रमाणीकरण की आवश्यकता है) |
सारांश और सर्वोत्तम अभ्यास
इस विस्तृत गाइड में, हमने सुरक्षित वेब एप्लिकेशन बनाने के लिए Node.js HTTPS मॉड्यूल और इसकी क्षमताओं का पता लगाया। यहां महत्वपूर्ण बिंदुओं और सर्वोत्तम प्रथाओं का सारांश दिया गया है:
महत्वपूर्ण Takeaways
सुरक्षा जाँच सूची
अपने HTTPS-सक्षम एप्लिकेशन को उत्पादन में विस्तारित करने से पहले, जांचें:
याद करना:
सुरक्षा एक सतत प्रक्रिया है. अपने एप्लिकेशन का नियमित रूप से ऑडिट करें, निर्भरता को अद्यतन रखें, और नवीनतम सुरक्षा सर्वोत्तम प्रथाओं और कमजोरियों के बारे में सूचित रहें।